<template>
  <div class="chart-header" v-if="chartData.aoi || chartData.op">
    <el-checkbox-group v-model="checkList" @input="changeRadio" v-if="ShowChangeRadio">
      <el-checkbox  label="aoi">AOI坐标</el-checkbox >
      <el-checkbox  label="op">OP坐标</el-checkbox >
    </el-checkbox-group>
    <el-popover
        title="过滤条件"
        ref="chartPopover"
        placement="top-start"
        width="700"
        @show="showFilter"
        @hide="cancelFilter"
        trigger="click"
    >
      <el-form ref="form" :model="searchForm" label-width="130px" v-if="show">
        <el-row>
          <el-col :span="12" class="detect-container">
            <h4 class="filter-title">检出设备</h4>
            <el-form-item label="AOI code"  v-if="!showArBr">
              <el-select
                  style="width: 100%;"
                  v-model="searchForm.aoiCode"
                  filterable
                  multiple
                  clearable
                  placeholder="请选择"
                  collapse-tags
              >
                <el-option
                    v-for="(item,index) in selectOptions.aoiCode"
                    :key="index"
                    :label="item"
                    :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检出设备"  v-if="!showArBr">
              <el-cascader
                  style="width: 100%;"
                  popper-class="mapping_cascader"
                  placeholder="GLS-EQP ID/GLS-Unit ID"
                  v-model="searchForm.eqpUnit"
                  :options="selectOptions.eqpUnit"
                  :props="cascaderProps"
                  collapse-tags
                  clearable
                  filterable
              />
            </el-form-item>
            <el-form-item label="检出设备"  v-if="showArBr"> <!-- array 专用 -->
              <el-select
                  style="width: 100%;"
                  v-model="searchForm.brDefect"
                  filterable
                  multiple
                  clearable
                  placeholder="请选择"
                  collapse-tags
              >
                <el-option
                    v-for="(item,index) in selectOptions.brDefect"
                    :key="index"
                    :label="item"
                    :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="检出时间">
              <el-cascader
                  style="width: 100%;"
                  popper-class="mapping_cascader"
                  placeholder="日期/小时"
                  v-model="searchForm.checkOutDayHour"
                  :options="selectOptions.checkOutDayHour"
                  :props="cascaderProps"
                  collapse-tags
                  clearable
                  filterable
              />
            </el-form-item>
            <el-form-item label="AR Analysis code" v-if="showArBr">
              <el-select
                  style="width: 100%;"
                  v-model="searchForm.arAnalysisCode"
                  filterable
                  multiple
                  clearable
                  placeholder="请选择"
                  collapse-tags
              >
                <el-option
                    v-for="(item,index) in selectOptions.arAnalysisCode"
                    :key="index"
                    :label="item"
                    :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="BR Analysis code" v-if="showArBr">
              <el-select
                  style="width: 100%;"
                  v-model="searchForm.brAnalysisCode"
                  filterable
                  multiple
                  clearable
                  placeholder="请选择"
                  collapse-tags
              >
                <el-option
                    v-for="(item,index) in selectOptions.brAnalysisCode"
                    :key="index"
                    :label="item"
                    :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="product-container">
            <h4 class="filter-title">生产设备</h4>
            <el-form-item label="生产站点">
              <el-select
                  style="width: 100%;"
                  v-model="searchForm.glsOperCode"
                  filterable
                  multiple
                  clearable
                  placeholder="请选择"
                  collapse-tags
              >
                <el-option
                    v-for="(item,index) in selectOptions.glsOperCode"
                    :key="index"
                    :label="item"
                    :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="生产设备">
              <el-cascader
                  style="width: 100%;"
                  popper-class="mapping_cascader"
                  placeholder="GLS-EQP ID/GLS-Unit ID"
                  v-model="searchForm.glsEqpUnit"
                  :options="selectOptions.glsEqpUnit"
                  :props="cascaderProps"
                  collapse-tags
                  clearable
                  filterable
              />
            </el-form-item>
            <el-form-item label="生产时间">
              <el-cascader
                  style="width: 100%;"
                  popper-class="mapping_cascader"
                  placeholder="日期/小时"
                  v-model="searchForm.dayHour"
                  :options="selectOptions.dayHour"
                  :props="cascaderProps"
                  collapse-tags
                  clearable
                  filterable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <i class="el-icon-boe-shaixuan1" slot="reference"/>
      <div style="text-align: right;padding-top: 25px;">
        <el-button type="primary" @click="filterMapFinalData">确定</el-button>
        <el-button type="primary" plain @click="cancelFilter">取消</el-button>
      </div>
    </el-popover>
  </div>
</template>

<script>
import { isEmpty, intersection, cloneDeep, merge } from "lodash"
import methods from "./mixin/methods"

const cacheAOISearchList = {
  aoiCode: [],
  brDefect: [],
  eqpUnit: [],
  checkOutDayHour: [],
  glsOperCode: [],
  glsEqpUnit: [],
  dayHour: [],
  arAnalysisCode: [],
  brAnalysisCode: [],
}

const cacheOPSearchList = cloneDeep(cacheAOISearchList)

export default {
  mixins: [methods],
  props: {
    chartData: {
      type: Object,
      require: true,
      default: () => ({
        aoi: null,
        model: null,
        op: null,
        title: null,
      })
    },
    dataType: {
      type: Array,
      default: () => ["aoi", "op"],
    },
    showArBr: {
      type: Boolean,
      default: false
    },
    ShowChangeRadio: {
      type: Boolean,
      default: true
    },
    xLength: {
      type: Number,
      default: 2500
    },
    yLength: {
      type: Number,
      default: 2500
    },
  },
  data() {
    return {
      show: false,
      searchForm: {
        aoiCode: [],
        brDefect: [],
        eqpUnit: [],
        checkOutDayHour: [],
        glsOperCode: [],
        glsEqpUnit: [],
        dayHour: [],
        arAnalysisCode: [],
        brAnalysisCode: [],
      },
      searchFormCache: {
        aoiCode: [],
        brDefect: [],
        eqpUnit: [],
        checkOutDayHour: [],
        glsOperCode: [],
        glsEqpUnit: [],
        dayHour: [],
        arAnalysisCode: [],
        brAnalysisCode: [],
      },
      aoiCodeList: [],
      glsEqpUnitList: [],
      dayHourList: [],
      checkList: this.dataType,
      pointAOI: {},
      pointOP: {},
      selectOptions: {
        aoiCode: [],
        brDefect: [],
        eqpUnit: [],
        checkOutDayHour: [],
        glsOperCode: [],
        glsEqpUnit: [],
        dayHour: [],
        arAnalysisCode: [],
        brAnalysisCode: [],
      },
      cascaderProps: {
        multiple: true
      }
    }
  },
  methods: {
    initData() {
      for (let attr in this.searchFormCache) {
        this.searchFormCache[attr] = []
      }
      let point = {}
      this.checkList.forEach((i) => {
        if (i === 'aoi') {
          point = merge({}, point, this.pointAOI)
        }
        if (i === 'op') {
          point = merge({}, point, this.pointOP)
        }
      })
      let gatherData = []
      let normalData = []
      for (let attr in point) {
        let { flag, glassX, glassY, panelX, panelY } = point[attr]
        if (flag === -1) {
          normalData.push([glassX, glassY, panelX, panelY])
        } else {
          gatherData.push([glassX, glassY, panelX, panelY])
        }
      }
      return { gatherData, normalData }
    },
    changeRadio(val) {
      for (let attr in this.searchForm) {
        this.searchForm[attr] = []
      }
      let selectOptions = {}
      val?.forEach((i) =>{
        if (i === 'aoi') {
          selectOptions = merge({}, selectOptions, cacheAOISearchList)
        }
        if (i === 'op') {
          selectOptions = merge({}, selectOptions, cacheOPSearchList)
        }
      })
      this.$set(this, 'selectOptions', selectOptions)
      let { gatherData, normalData } = this.initData()
      this.$emit('setChartOption', this.getScatterOptions(gatherData, normalData, this.xLength, this.yLength))
    },
    showFilter() {
      for (let attr in this.searchFormCache) {
        this.searchForm[attr] = this.searchFormCache[attr]
      }
      this.show = true
    },
    cancelFilter() {
      for (let attr in this.searchForm) {
        this.searchForm[attr] = []
      }
      this.show = false
      this.$refs.chartPopover.doClose()
    },
    setCacheSearch() {
      for (let attr in this.searchFormCache) {
        this.searchFormCache[attr] = this.searchForm[attr]
      }
    },
    filterMapFinalData() {//筛选逻辑：三个条件时，找出3个条件的交集，两个条件时，找出2个条件的交集，一个条件时，找出该条件的所有数据，0个条件时，找出所有数据
      const isInit = Object.keys(this.searchForm).every(key => !this.searchForm[key].length)
      if (isInit) {
        const { gatherData, normalData } = this.initData()
        this.$emit('setChartOption', {
          series: [
            { data: gatherData },
            { data: normalData }
          ]
        })
        this.cancelFilter()
        return
      }

      let selectedChartData = {}
      this.checkList?.forEach((i) =>{
        selectedChartData = merge({}, selectedChartData, this.chartData[i])
      })
      const selectedOptions = {
        aoiCode: [],
        brDefect: [],
        eqpUnit: [],
        checkOutDayHour: [],
        glsOperCode: [],
        glsEqpUnit: [],
        dayHour: [],
        arAnalysisCode: [],
        brAnalysisCode: [],
      }
      Object.keys(this.searchForm).forEach((key) => {
        const treeKey = `${key}Tree`
        const treeData = selectedChartData[treeKey]
        for (const item of this.searchForm[key]) {
          if (Array.isArray(item)) {
            treeData[item[0]][item[1]]?.length && selectedOptions[key].push(...treeData[item[0]][item[1]])
          } else {
            treeData[item]?.length && selectedOptions[key].push(...treeData[item])
          }
        }
      })
      let allFilterSames = []
      if (selectedOptions.length === 1) {
        allFilterSames = selectedOptions[0]
      } else {
        allFilterSames = intersection(...Object.values(selectedOptions).filter(item => item.length))
      }
      let gatherData = []
      let normalData = []
      for (let item of allFilterSames) {
        let { flag, glassX, glassY, panelX, panelY } = selectedChartData.point[item]
        if (flag === -1) {
          normalData.push([glassX, glassY, panelX, panelY])
        } else {
          gatherData.push([glassX, glassY, panelX, panelY])
        }
      }
      this.$emit('setChartOption', {
        series: [
          { data: gatherData },
          { data: normalData }
        ]
      })
      this.setCacheSearch()
      this.cancelFilter()
    },
    transformTreeByMap(obj) {
      return (obj && Object.keys(obj)?.length) ? Object.keys(obj).map(key => {
        return {
          label: key,
          value: key,
          children: Object.keys(obj[key])?.length ? Object.keys(obj[key]).map(subKey => ({
            label: subKey,
            value: subKey
          })) : []
        }
      }) : []
    },
    cacheSearchList(list, data) {
      Object.keys(list).forEach(key => {
        const treeKey = `${key}Tree`
        list[key] = ['aoiCode', 'brDefect', 'glsOperCode', 'arAnalysisCode', 'brAnalysisCode'].includes(key) ? Object.keys(data[treeKey]) : this.transformTreeByMap(data[treeKey])
      })
    }
  },
  mounted() {
    let { aoi, op } = this.chartData
    if (!isEmpty(aoi)) {
      this.pointAOI = Object.freeze(aoi.point)
      this.cacheSearchList(cacheAOISearchList, aoi)
    }
    if (!isEmpty(op)) {
      this.pointOP = Object.freeze(op.point)
      this.cacheSearchList(cacheOPSearchList, op)
    }
    this.changeRadio(this.dataType)
  }
}
</script>

<style scoped lang="stylus">
.chart-header
  width 90%;
  position: absolute;
  top: 10px;
  left: 40px;
  z-index: 99;

  .el-icon-boe-shaixuan1
    font-size: 30px;
    position: absolute;
    top: -10px;
    right: 20px;
    cursor: pointer;
    z-index: 99;


.el-row
  .filter-title
    text-align center

.detect-container
  padding-right 10px
  border-right 1px solid rgba(0, 0, 0, .2)

.product-container
  padding-left 10px
</style>
